package servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.ICommand;
import command.carroCompras.AdicionarProdutoCarroComprasCommand;
import command.carroCompras.AdicionarUsuarioCommand;

/**
 * Servlet implementation class ControllerServlet
 */
public class ControllerServlet extends HttpServlet {
       
	private HashMap<String, ICommand> map;
	

	public void init(ServletConfig config) throws ServletException {
		map = new HashMap<String, ICommand>();		
		map.put("addProdutoNoCarrinho", new AdicionarProdutoCarroComprasCommand());
		map.put("addUsuario", new AdicionarUsuarioCommand());
	}
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String acao = request.getParameter("acao");
		
		ICommand command = this.find(acao);
		String url = command.execute(request);

		RequestDispatcher d = request.getRequestDispatcher(url);
		d.forward(request, response);	
	}
	
	private ICommand find(String acao) throws ServletException{
		// Verifica se foi informada alguma pagina que nao esta mapeada no HashMap
		if (!map.containsKey(acao)) {
			throw new ServletException("Página não encontrada: " + acao);
		}
		return (ICommand) map.get(acao);
	}
}